package com.ynny.usermanager.dao;

import com.ynny.usermanager.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;


    @Override
    public User selectUserById(Integer id) {

        String sql = "select * from user where id=?";
        User user = jdbcTemplate.queryForObject(sql,
                new BeanPropertyRowMapper<>(User.class),
                id);

        return user;
    }

    @Override
    public List<User> selectUsers() {

        String sql = "select * from user";
        List<User> users = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<>(User.class));

        return users;
    }

    @Override
    public int insertUser(User user) {

        String sql = "insert into user(username, password, age) values ( ?, ?, ?)";

        int i = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getAge());
        return i;
    }

    @Override
    public int updateUser(User user) {

        String sql = "update user set username = ?, password = ?, age = ? where id=?";

        int i = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getAge(),
                user.getId());
        return i;
    }

    @Override
    public int deleteUserById(Integer id) {

        String sql = "delete from user where id=?";

        int i = jdbcTemplate.update(sql, id);
        return i;
    }
}
